package com.gl.saasservice.smartlock.haixiaoke;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.gl.common.vo.ResultBean;
import com.gl.saasservice.entity.SmartLockCard;
import com.mzj.saas.commons.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author Dell
 * @Date 2023/9/8
 **/
@Slf4j
@Service
public class SmartLockHxkService {

    @Value("${haiXiaoKe.url}")
    private String haiXiaoKeUrl;
    @Value(("${haiXiaoKe.appId}"))
    private String haiXiaoKeAppid;
    @Value("${haiXiaoKe.appSecret}")
    private String haiXiaoKeAppSecret;

//    @Autowired
//    private RedisTemplate redisTemplate;
    @Autowired
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    public SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    public String haiXiaoKeParseDate(Date date) {
        if (date == null) {
            date = new Date();
        }
        return simpleDateFormat.format(date);
    }

    /**
     * 获取嗨小克平台token
     *
     * @return token
     */
    public String getToken() {
        String token = redisTemplate.opsForValue().get("sys_haiXiaoKeToken");
        if (StringUtils.isEmpty(token)) {
            try {
                Map<String, Object> paramsMap = new HashMap<>(4);
                String nowTime = this.haiXiaoKeParseDate(null);
                paramsMap.put("appId", haiXiaoKeAppid);
                paramsMap.put("appSecret", haiXiaoKeAppSecret);
                paramsMap.put("sendTime", nowTime);
                paramsMap.put("randNonce", "123456");
                log.info("嗨小克--鉴权接口请求参数：{}",paramsMap);
                HttpResponse response = HttpRequest.post(haiXiaoKeUrl + "/login").body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
                log.info("嗨小克--鉴权接口响应参数：{}",response.body());
                if (HttpStatus.HTTP_OK == response.getStatus()) {
                    JSONObject jsonObject = JSONObject.parseObject(response.body());
                    String code = jsonObject.getString("code");
                    if ( "0".equals(code)) {
                        JSONObject result = jsonObject.getJSONObject("result");
                        token = "Bearer " + result.getString("accessToken");
                        Integer expiresIn = result.getInteger("expiresIn");
                        redisTemplate.opsForValue().set("sys_haiXiaoKeToken",  token, expiresIn / 10, TimeUnit.MILLISECONDS);
                    } else {
                        log.error("嗨小克--鉴权请求响应数据异常：{}", jsonObject);
                    }
                } else {
                    log.error("嗨小克--鉴权请求失败，code：{}；body:{}", response.getStatus(), response.body());
                }
            } catch (Exception e) {
                log.error("嗨小克--鉴权请求异常：{}", e.getMessage(), e);
            }
        }
        return token;
    }

    /**
     * 授权门卡信息
     * @param sn
     * @param smartLockCard
     * @return
     */
    public ResultBean<String> identityCardUnlocking(String sn, SmartLockCard smartLockCard) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("嗨小克--授权智能锁用户密码接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        try {
            Map<String, Object> paramsMap = new HashMap<>(4);
            String notTime = this.haiXiaoKeParseDate(null);
            paramsMap.put("sendTime", notTime);
            paramsMap.put("randNonce", "123456");
            paramsMap.put("deviceMac", sn);
            //用户id
//            paramsMap.put("userIndex", smartLock.getIdentification());
//            paramsMap.put("mobile", smartLock.getMobile());
//            paramsMap.put("userName", smartLock.getUserName());
            //身份证授权
            //角色，0普通用户,1管理员，2保洁
            paramsMap.put("userRole", "0");
            paramsMap.put("idNumber", smartLockCard.getCardNumber());
            paramsMap.put("cardNo", smartLockCard.getCardNumber());
            paramsMap.put("startTime", this.haiXiaoKeParseDate(smartLockCard.getStartTime()));
            paramsMap.put("endTime", this.haiXiaoKeParseDate(smartLockCard.getEndTime() == null ? this.addTime(new Date()) : smartLockCard.getEndTime()));
            log.info("嗨小克--门卡授权请求：{}",paramsMap);
            HttpResponse response = HttpRequest.post(haiXiaoKeUrl + "/lock/addUser")
                    .header("Authorization", token).form(paramsMap).timeout(20000).execute();
            log.info("嗨小克--门卡授权响应：{}",response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String code = jsonObject.getString("code");
                if ( "0".equals(code)) {
                    //维护数据库数据
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    objectResultBean.setResultData(smartLockCard.getCardNumber());
                    return objectResultBean;
                } else {
                    log.error("嗨小克--授权门锁用户门卡请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("添加失败：" + jsonObject.getString("message"));
                }
            } else {
                log.error("嗨小克--授权门锁用户门卡请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("添加门卡信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("添加门卡信息请求异常");
            log.error("嗨小克--授权门锁用户门卡请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    /**
     * 删除IC卡信息
     * @param sn
     * @param identification
     * @return
     */
    public ResultBean<String> deleteIdentityCardUnlocking(String sn,String identification) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            objectResultBean.setMsg("获取token失败");
            log.error("嗨小克--删除智能锁用户门卡接口--token为空");
            return objectResultBean;
        }
        try {
            Map<String, Object> paramsMap = new HashMap<>(4);
            String notTime = this.haiXiaoKeParseDate(null);
            paramsMap.put("sendTime", notTime);
            paramsMap.put("randNonce", "123456");
            paramsMap.put("deviceMac", sn);
            paramsMap.put("idNumber", identification);
            log.info("嗨小克--门卡删除请求：{}",paramsMap);
            HttpResponse response = HttpRequest.post(haiXiaoKeUrl + "/lock/removeUser").header("Authorization", token).body(JSONObject.toJSONString(paramsMap)).timeout(20000).execute();
            log.info("嗨小克--门卡删除响应：{}",response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                String code = jsonObject.getString("code");
                if ( "0".equals(code)) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    return objectResultBean;
                } else {
                    objectResultBean.setMsg("删除信息失败");
                    log.error("嗨小克--删除门锁用户门卡请求响应数据异常：{}", jsonObject);
                }
            } else {
                objectResultBean.setMsg("删除信息响应失败");
                log.error("嗨小克--删除门锁用户门卡请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            objectResultBean.setMsg("删除身份信息请求异常");
            log.error("嗨小克--删除门锁用户门卡请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    public Date addTime(Date nowTime){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowTime);
        calendar.add(Calendar.YEAR, 100);
        return calendar.getTime();
    }

}
